import FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

/**
 * 导出表格
 * @param {*} table  this.$refs.table.$el 表格节点
 */
export function exportToExcel(table) {
    // console.log('导出表格',table);
    let tableCopy = table.cloneNode(true); // 创建表格副本
    let rows = tableCopy.getElementsByTagName('tr');
    for (let i = 0; i < rows.length; i++) {
        let cells = rows[i].getElementsByTagName('td');
        rows[i].deleteCell(cells.length - 1);
    }
    let vb = XLSX.utils.table_to_book(tableCopy); // 将表格转换为工作簿
    let vbout = XLSX.write(vb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
    });

    try {
        FileSaver.saveAs(new Blob([vbout], { type: 'application/octet-stream' }), 'data.xlsx');
    } catch (e) {
        if (typeof console !== 'undefined') console.log(e, vbout);
    }
}